<template>
  <TopBar></TopBar>
  <el-container class="fruit">
    <el-aside class="hotsell_bar">
      <div style="font-size:20px ;padding-top: 20px ;margin-bottom: 20px">商家热销：</div>
      <div v-for="item in hotsellItems" @click="jumpDetail(item.itemID)" class="hot_card"
        style="width: 80%;margin: auto;margin-bottom: 2vh;">
        <div class="card_img">
          <el-image class="card_img_el"
            :src="`https://zizi-1325809325.cos.ap-guangzhou.myqcloud.com/商品列表/List/${item.itemImg}.jpg`"
            fit="cover"></el-image>
        </div>
        <span style="font-weight: bold;">{{ item.itemName }}</span>
      </div>
    </el-aside>

    <el-container class="fruit-item">
      <el-header class="category_bar" style="width: 99%;">
        <div style="width:100px;font-weight: bold;color: white;margin-top: 2vh;">
          分类：
        </div>
        <el-button type="default" text bg @click="goBack"
          style="margin-right: 2vh;font-weight: bold;margin-top: 2vh;">返回</el-button>
        <!-- 根据当前分类层级显示不同的分类按钮 -->

        <!-- 一级分类展示 -->
        <div v-if="currentLevel === 1">
          <el-button type="plain" text bg v-for="item in category_list" :key="item.categoryId"
            @click="goToSubCategory(item, 1)" style="font-weight: bold;margin-top: 2vh;">
            {{ item.categoryName }}
          </el-button>
        </div>

        <!-- 二级分类展示 -->
        <div v-if="currentLevel === 2">
          <el-button type="plain" text bg v-for="item in type_list" :key="item.categoryId"
            @click="goToSubCategory(item, 2)" style="font-weight: bold;margin-top: 2vh;">
            {{ item.categoryName }}
          </el-button>
        </div>

        <!-- 三级分类展示 -->
        <div v-if="currentLevel === 3">
          <el-button type="plain" text bg v-for="item in class_list" :key="item.categoryId"
            @click="goToSubCategory(item, 3)" style="font-weight: bold;margin-top: 2vh;">
            {{ item.categoryName }}
          </el-button>
        </div>
      </el-header>

      <el-main class="fruit_bar" style=" background-color: #E9EEF3;width: 99%;">
        <div class="card-container">
          <div v-for="item in items" @click="jumpDetail(item.itemID)" class="card">
            <div class="card_img">
              <el-image class="card_img_el"
                :src="`https://zizi-1325809325.cos.ap-guangzhou.myqcloud.com/商品列表/List/${item.itemImg}.jpg`"
                fit="cover"></el-image>
            </div>
            <div class="card_title">
              <h3>{{ item.itemName }}</h3>
            </div>
            <div class="card_tag">
              <el-tag v-for="tag in item.itemTags" :key="tag">{{ tag }}</el-tag>
            </div>
            <div class="card_price">
              <h4>{{ item.itemPrice }}元</h4>
            </div>
            <div v-if="item.free">
              <el-image style="width: 50%;float: right;margin-top: -2vh;" src="https://zizi-1325809325.cos.ap-guangzhou.myqcloud.com/icons/daydayfurit.png"></el-image>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
  </el-container>
  <Footer></Footer>
</template>

<script setup>
import TopBar from '@/component/TopBar.vue'
import Footer from '@/component/Footer.vue'
import { ref, onMounted } from 'vue';
import request from "../../utils/request";
import { useRoute, useRouter } from "vue-router";
import { ElNotification } from 'element-plus'
import { ElLoading } from 'element-plus'
// 获取路由器实例
const router = useRouter();
const route = useRoute();

// 定义响应式变量
const items = ref([])
const items_list = ref([]);      // 商品列表
const category_list = ref([]);   // 一级分类列表
const type_list = ref([]);       // 二级分类列表
const class_list = ref([]);      // 三级分类列表

const categoryId = ref(null);    // 当前一级分类ID
const typeId = ref(null);        // 当前二级分类ID
const classId = ref(null);       // 当前三级分类ID

const currentLevel = ref(1);     // 当前分类层级，1为一级分类，2为二级分类，3为三级分类

const hotsellItems = ref([]);      // 热销商品


const loadCategory = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '吱吱正在努力查找分类...',
    background: 'rgba(0,0,0,0.7)'
  })
  try {
    const res = await request.get('/api/item/getCategory')
    console.log(res);
    items_list.value = res;
    loading.close();

    // 使用递归遍历树形结构，将分类分配到相应的层级
    const distributeCategories = (categories) => {
      categories.forEach(item => {
        // 按照分类层级分配
        if (item.categoryLevel === 1) {
          category_list.value.push(item);
          if (item.children) {          // 递归处理二级分类
            distributeCategories(item.children);
          }
        } else if (item.categoryLevel === 2) {
          type_list.value.push(item);
          if (item.children) {          // 递归处理三级分类
            distributeCategories(item.children);
          }
        } else if (item.categoryLevel === 3) {
          class_list.value.push(item);
        }
      });
    };

    // 调用递归方法分配数据
    distributeCategories(items_list.value);

    // 如果有 categoryId，显示对应的二级分类或三级分类
    if (categoryId.value) {
      type_list.value = category_list.value.find(item => item.categoryId === categoryId.value)?.children || [];
    }
    if (typeId.value) {
      class_list.value = type_list.value.find(item => item.categoryId === typeId.value)?.children || [];
    }

  } catch (error) {
    console.error("Failed to load categories", error);
  }
};

// 通过分类层级来加载子分类
const goToSubCategory = (category, level) => {
  if (level === 1) {
    categoryId.value = category.categoryId;
    typeId.value = null;  // 清空二级分类
    classId.value = null; // 清空三级分类
    currentLevel.value = 2;
    type_list.value = category.children || [];  // 加载二级分类的子分类
    loadItems();  // 获取该三级分类下的商品
    router.push(`/f/${category.categoryId}`);  // 跳转到一级分类
  } else if (level === 2) {
    typeId.value = category.categoryId;
    classId.value = null; // 清空三级分类
    currentLevel.value = 3;
    class_list.value = category.children || [];  // 加载三级分类的子分类
    loadItems();
    router.push(`/f/${category.categoryId}`);  // 跳转到二级分类
  } else if (level === 3) {  // 对应三级分类
    classId.value = category.categoryId;
    currentLevel.value = 4;  // 设置为三级分类
    console.log(category.categoryId)
    loadItems();
    router.push(`/f/${category.categoryId}`);  // 跳转到三级分类
  }
};

// 加载商品列表
const loadItems = async () => {
  console.log("loadItems");
  const params = {};
  if (classId.value) {
    params.classId = classId.value;
  } else if (typeId.value) {
    params.typeId = typeId.value;
  } else if (categoryId.value) {
    params.categoryId = categoryId.value;
  }

  try {
    const res = await request.get('/api/item/findItemsByCategoryWithFree', { params });
    console.log('商品列表:', res);
    items.value = res.data || []; // 将商品列表存储到 items 变量中
    items.value.forEach(item => {
      item.itemTags = item.itemTags.split('/');
    })
  } catch (error) {
    console.error("Failed to load items", error);
  }
};



const goBack = () => {
  if (currentLevel.value === 4) {
    // 当前处于三级分类的子分类，返回到三级分类
    currentLevel.value = 3;
    class_list.value = type_list.value.find(item => item.categoryId === typeId.value)?.children || [];
    classId.value = null; // 清空三级分类ID
    loadItems();  // 加载三级分类对应的商品
    router.push(`/f/${typeId.value}`); // 返回到二级分类
  } else if (currentLevel.value === 3) {
    // 当前处于三级分类，返回到二级分类
    currentLevel.value = 2;
    type_list.value = category_list.value.find(item => item.categoryId === categoryId.value)?.children || [];
    typeId.value = null; // 清空二级分类ID
    loadItems();  // 加载二级分类对应的商品
    router.push(`/f/${categoryId.value}`); // 返回到一级分类
  } else if (currentLevel.value === 2) {
    // 当前处于二级分类，返回到一级分类
    currentLevel.value = 1;
    category_list.value = items_list.value; // 所有一级分类
    categoryId.value = null; // 清空一级分类ID
    loadItems();  // 加载一级分类对应的商品
    router.push('/fruitCentre'); // 返回到一级分类（fruitCentre页面）
  } else {
    // 如果不在任何分类层级上，返回首页或其他逻辑
    router.push('/');  // 假设首页路由是 '/'
  }
};


onMounted(() => {

  loadhotsellitem();
  loadCategory();  // 加载分类数据
  // 检查是否有路由中的分类参数，进行相应的加载
  const categoryIdFromRoute = route.params.categoryId;
  const typeIdFromRoute = route.params.typeId;
  const classIdFromRoute = route.params.classId;

  if (categoryIdFromRoute) {
    categoryId.value = categoryIdFromRoute;
    currentLevel.value = 2;  // 假设跳转到一级分类页面时直接显示二级分类
    loadItems();  // 加载该分类下的商品
  } else if (typeIdFromRoute) {
    typeId.value = typeIdFromRoute;
    currentLevel.value = 3;  // 跳转到二级分类页面，显示三级分类
    loadItems();  // 加载该分类下的商品
  } else if (classIdFromRoute) {
    classId.value = classIdFromRoute;
    currentLevel.value = 4;  // 跳转到三级分类页面
    loadItems();  // 加载该分类下的商品
  } else {
    loadItems();  // 没有分类ID时加载所有商品
  }
});

const loadhotsellitem = () => {
  request.get('/api/item/selectRandomItems').then(res => {
    hotsellItems.value = res.data;
  })
}

// 跳转到商品详情页
const jumpDetail = (itemId) => {
  router.push(`/desc/${itemId}`);
};


// 选择某个商品时的处理
const handleSelect = (item) => {
  console.log('选中的商品:', item.itemID);
  jumpDetail(item.itemID);
};

// 处理点击图标事件
const handleIconClick = () => {
  console.log('搜索图标点击');
};
</script>



<style scoped>
.top_bar {
  width: 100%;
  height: 10vh;
  /* background-color: wheat; */
  display: flex;
}

.top_bar img {
  width: 20vh;
  height: auto;
  margin-left: 15vh;
}

.top_bar .search {
  width: 100vh;
  margin: auto;
  margin-left: 10vh;
  display: flex;
}

.search .search_btn_v {
  background-color: greenyellow;
  font-size: 2.5vh;
}

/* 导航栏 */
.select_bar {
  width: 100%;
  height: 5vh;
  display: flex;
}

.select_btn {
  margin: auto;
  font-weight: bold;
  font-size: 18px;
}

.hotsell_bar {
  background-color: #d3e6e3;
  text-align: center;
  width: 30vh;
  margin: 0px 20px;
}

.card_img {
  transition: all 0.3s ease;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.card_img:hover {
  transform: scale(1.02);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}

.category_bar {
  display: flex;
  background-color: #208344;
  color: #333;
  height: 10vh;
  padding-top: 17px;
  margin-bottom: 20px;
}

.card-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: stretch;
  gap: 1vw;
}

.card {
  margin-left: 4.4vh;
  width: 15%;
  height: 30vh;
}

.hotsellcard {
  margin-left: 4.4vh;
  width: 13%;
  height: 30vh;
}

.card:hover {
  outline: red 1px solid;
}

.card_img_el {
  border-radius: 3px;
  width: 100%;
  height: 16vh;
}

.card_title h3 {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  font-size: 1.9vh;
  font-weight: normal;
}

.card_tag {
  display: flex;
  gap: 8px;
}

.card_price {
  display: flex;
}

.card_price h4 {
  color: red;
  font-weight: bold;
  margin-top: 0vh;
  font-size: 2.4vh;
}</style>